package com.qifan.energy.global;

import android.app.Application;
import android.content.Context;
import android.os.Environment;
import android.os.Handler;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.ProcessUtils;
import com.blankj.utilcode.util.Utils;
import com.qifan.energy.BuildConfig;
import com.qifan.energy.R;
import com.orhanobut.logger.AndroidLogAdapter;
import com.orhanobut.logger.Logger;
import com.tencent.bugly.Bugly;
import com.tencent.bugly.beta.Beta;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.socialize.PlatformConfig;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;

public class MyApplication extends Application {

    /* bugly APP_ID */
    private static final String BUGLY_APP_ID = "c409929be9";
    public static MyApplication application;
    private static Context context = null;
    private static Handler handler = null;
    public static Thread mainThread = null;
    private static int mainThreadId = 0;
    private static Boolean isDebug;

    @Override
    public void onCreate() {
        super.onCreate();

        context = getApplicationContext();
        handler = new Handler();
        mainThread = Thread.currentThread();
        mainThreadId = android.os.Process.myTid();//当前线程id，此处是主线程id


        /*x.Ext.init(this);
        x.Ext.setDebug(false); //输出debug日志，开启会影响性能*/
        application = this;
        /* 初始化日志组件 */
        Logger.addLogAdapter(new AndroidLogAdapter() {
            @Override
            public boolean isLoggable(int priority, @Nullable String tag) {
                return BuildConfig.DEBUG;
            }
        });

        //初始化工具类
        Utils.init(this);
        //初始化Bugly
        initBugly();
        //初始化Umeng
        initUmeng();
        //初始化ZXingLibrary
        ZXingLibrary.initDisplayOpinion(this);
    }

    public static MyApplication getApplication() {
        return application;
    }

    public static Context getContext() {
        return context;
    }

    public static Handler getHandler() {
        return handler;
    }

    public static int getMainThreadid() {
        return mainThreadId;
    }

    /* 是否Debug环境 */
    public static boolean isDebug() {
        return BuildConfig.DEBUG;
    }

    /* 初始化Bugly */
    private void initBugly() {
        // 获取当前包名
        String packageName = getApplication().getPackageName();
        // 获取当前进程名
        String processName = ProcessUtils.getCurrentProcessName();
        // 设置是否为上报进程
        CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(getApplicationContext());
        strategy.setUploadProcess(processName == null || processName.equals(packageName));
        //初始化bugly
        // 这里实现SDK初始化，appId替换成你的在Bugly平台申请的appId
        // 调试时，将第三个参数改为true
        Bugly.init(getApplication(), BUGLY_APP_ID, isDebug(),strategy);
        initBeta(getApplication());
    }

    private void initBeta(Context context){
        /***** Beta高级设置 *****/
        /**
         * true表示app启动自动初始化升级模块;
         * false不会自动初始化;
         * 开发者如果担心sdk初始化影响app启动速度，可以设置为false，
         * 在后面某个时刻手动调用Beta.init(getApplicationContext(),false);
         */
        Beta.autoInit = true;

        /**
         * true表示初始化时自动检查升级;
         * false表示不会自动检查升级,需要手动调用Beta.checkUpgrade()方法;
         */
        Beta.autoCheckUpgrade = true;

        /**
         * 设置升级检查周期为60s(默认检查周期为0s)，60s内SDK不重复向后台请求策略);
         */
        Beta.upgradeCheckPeriod = 60 * 1000;

        /**
         * 设置启动延时为1s（默认延时3s），APP启动1s后初始化SDK，避免影响APP启动速度;
         */
        //        Beta.initDelay = 1 * 1000;

        /**
         * 设置通知栏大图标，largeIconId为项目中的图片资源;
         */
        Beta.largeIconId = R.mipmap.ic_launcher;

        /**
         * 设置状态栏小图标，smallIconId为项目中的图片资源Id;
         */
        Beta.smallIconId = R.mipmap.ic_launcher;

        /**
         * 设置更新弹窗默认展示的banner，defaultBannerId为项目中的图片资源Id;
         * 当后台配置的banner拉取失败时显示此banner，默认不设置则展示“loading“;
         */
        Beta.defaultBannerId = R.mipmap.ic_launcher;

        /**
         * 设置sd卡的Download为更新资源保存目录;
         * 后续更新资源会保存在此目录，需要在manifest中添加WRITE_EXTERNAL_STORAGE权限;
         */
        Beta.storageDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);

        /**
         * 点击过确认的弹窗在APP下次启动自动检查更新时会再次显示;
         */
        Beta.showInterruptedStrategy = true;

        /**
         * 只允许在MainActivity上显示更新弹窗，其他activity上不显示弹窗;
         * 不设置会默认所有activity都可以显示弹窗;
         */
        /*Beta.canShowUpgradeActs.add(MainActivity.class);*/

        /***** 统一初始化Bugly产品，包含Beta *****/
        Bugly.init(context, BUGLY_APP_ID, isDebug());
    }

    /* 初始化友盟组件 */
    private void initUmeng() {
        /*UMConfigure.init(this
                ,"5a12384aa40fa3551f0001d1"
                ,"umeng",UMConfigure.DEVICE_TYPE_PHONE,"");*/

        UMConfigure.init(this, BuildConfig.UMENG_APPKEY, "umeng",
                UMConfigure.DEVICE_TYPE_PHONE, BuildConfig.UMENG_MESSAGE_SECRET);
        PlatformConfig.setWeixin(BuildConfig.WX_APPKEY, BuildConfig.WX_APP_SECRET);

        /*InAppMessageManager.getInstance(this).setInAppMsgDebugMode(BuildConfig.DEBUG);
        PlatformConfig.setWeixin(BuildConfig.WX_APPKEY, BuildConfig.WX_APP_SECRET);
        // 选用AUTO页面采集模式
        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        *//*
         *         //获取消息推送代理示例
         * 友盟推送客户端
         *//*
        PushAgent mPushAgent = PushAgent.getInstance(this);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                devToken = deviceToken;
                Logger.i("注册成功：deviceToken：-------->  " + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                Logger.e("注册失败：-------->  " + "s:" + s + ",s1:" + s1);
            }
        });
        mPushAgent.setNotificationClickHandler(new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage uMessage) {
                if (pushClickListener != null) {
                    pushClickListener.onPushClick(uMessage.title, uMessage.text, uMessage.extra);
                    return;
                }

                // 隐式地通过Schema打开Activity,比如跳转新界面,在androidManifest声明了Schema
                Intent intent = new Intent("treebearxiaok://treebearxiaok.com");
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Bundle bundle = new Bundle();
                bundle.putString(Keys.TITLE, uMessage.title);
                bundle.putString(Keys.CONTENT, uMessage.text);
                if (uMessage.extra.containsKey("type")) {
                    bundle.putInt(Keys.TYPE, Integer.valueOf(uMessage.extra.get("type")));
                }
                context.startActivity(intent);
            }
        });*/
    }
}
